package br.com.dwii.tpg2.servlet;

import br.com.dwii.tpg2.entidade.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Diego
 */
public class AnimalSrv extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if ("getCidades".equals(request.getParameter("action"))) {
            response.getWriter().write(getCidades(Long.valueOf(request.getParameter("idUf"))));
        } else {
            String url = "index.jsp";
            
            Responsavel resp = new Responsavel();
            Contato contato = new Contato();
            Caracteristica carac = new Caracteristica();
            Animal animal = new Animal();
            
            Map params = new HashMap();
            
            // Check that we have a file upload request
            if (ServletFileUpload.isMultipartContent(request)) {
                try {
                    // Create a factory for disk-based file items
                    FileItemFactory factory = new DiskFileItemFactory();
                    // Create a new file upload handler
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    // Parse the request
                    List items = upload.parseRequest(request);
                    // Process the uploaded items
                    Iterator iter = items.iterator();
                    while (iter.hasNext()) {
                        FileItem item = (FileItem) iter.next();
                        if (item.isFormField()) {
                            params.put(item.getFieldName(), item.getString());
                        } else {
                            if (item.get().length > 0) {
                                animal.setFoto(item.get());
                                animal.setContentType(item.getContentType());
                            }
                        }
                    }
                } catch (FileUploadException ex) {
                    Logger.getLogger(AnimalSrv.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            // Responsável
            resp.setNome(String.valueOf(params.get("resp_nome")));
            resp.setCpf(String.valueOf(params.get("resp_cpf")).replace(".", "").replace("-", ""));
            resp.setIdUf(params.get("resp_uf") == null ? 0L : Long.valueOf(params.get("resp_uf").toString()));
            resp.setIdCidade(params.get("resp_cid") == null ? 0L : Long.valueOf(params.get("resp_cid").toString()));

            // Contato
            contato.setNome(String.valueOf(params.get("cont_nome")));
            contato.setEmail(String.valueOf(params.get("cont_email")));
            if (params.get("cont_fone") != null) {
                contato.setFone(String.valueOf(params.get("cont_fone")).replace("(", "").replace(")", "").replace("-", ""));
            }

            // Caracteristica
            carac.setFlagTipoAnimal(String.valueOf(params.get("tipo_animal")));
            carac.setFlagSexo(String.valueOf(params.get("sexo")));
            carac.setFlagIdade(String.valueOf(params.get("idade")));
            carac.setFlagPorte(String.valueOf(params.get("porte")));
            carac.setFlagPelagem(String.valueOf(params.get("pelagem")));
            carac.setFlagRaca(String.valueOf(params.get("raca")));
            carac.setFlagEsterilizado(params.get("saude_1") == null ? "N" : "S");
            carac.setFlagVacinado(params.get("saude_2") == null ? "N" : "S");
            carac.setFlagVermifugado(params.get("saude_3") == null ? "N" : "S");

            // Animal
            animal.setNome(String.valueOf(params.get("nome")));
            animal.setTemperamento(String.valueOf(params.get("temperamento")));
            animal.setHistorico(String.valueOf(params.get("historico")));

            try {
                animal.setIdResponsavel(resp.save());
                animal.setIdContato(contato.save());
                animal.setIdCaracteristica(carac.save());
                animal.save();
            } catch (SQLException ex) {
                url += "?error=true";
            }

            response.sendRedirect(url);
        }
    }

    private String getCidades(Long idUf) {
        StringBuilder str = new StringBuilder();
        try {
            str.append("<select id=\"resp_cid\" name=\"resp_cid\">\n");
            str.append("<option value=\"\">Selecione</option>\n");
            for (Cidade cid : Cidade.getListAllByUf(idUf)) {
                str.append("<option id=\"").append(cid.getId()).append("\" value=\"");
                str.append(cid.getId()).append("\">");
                str.append(new String(cid.getNome().getBytes("UTF-8"), "ISO-8859-1")).append("</option>\n");
            }
            str.append("</select>\n");
        } catch (SQLException ex) {
            Logger.getLogger(AnimalSrv.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(AnimalSrv.class.getName()).log(Level.SEVERE, null, ex);
        }
        return str.toString();
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}
